#!/usr/bin/env python

import tarfile
import os
import sys
import shutil
import utility

class Plugins:
    """ build_tarball is the location of the NAVL tarball
        you want to add plugins to. plugin_dir is a folder
        containing only the plugin tarballs you wnt to add
        to the specified NAVL build. """
    def __init__(self, build_tarball, plugin_dir):
        self.plugin_dir = plugin_dir
        self.build_tarball = build_tarball

    def extract_build(self):
        """ Extracts a NAVL build to the builds dir """
        build_destination = "/root/builds/"
        if tarfile.is_tarfile(self.build_tarball):
            try:
                new_build = tarfile.open(str(self.build_tarball))
                new_build.extractall(path=build_destination)
                new_build.close()
            except Exception, error_msg:
                print error_msg
        else:
            print "Not a file: %s" % self.build_tarball
            
    def copy_plugins(self, plugin_dest):
        plugins = utility.Directory(self.plugin_dir, ".plg")
        for files in plugins:
            shutil.copy(files, plugin_dest)

    def extract_plugins(self):
        """ Extracts plugins and adds them to the specified NAVL build """
        plugins = utility.Directory(self.plugin_dir, ".tar.gz")
        plugin_dest = self.build_tarball[:-7] + "/plugins"
        for plg in plugins:
            if tarfile.is_tarfile(plg):
                try:
                    plg_tar = tarfile.open(plg)
                    plg_tar.extractall(path=self.plugin_dir)
                    plg_tar.close()
                    os.remove(plg)
                except Exception as error_msg:
                    print error_msg
        self.copy_plugins(plugin_dest)
        self.cleanup(self.plugin_dir)

    def cleanup(self, plugin_dir):
        for path, dirs, files in os.walk(plugin_dir):
            for dir in dirs:
                dir = os.path.join(path, dir)
                if os.path.isdir(dir):
                    shutil.rmtree(dir)